<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="批次号" prop="batchNo">
        <el-select v-model="queryParams.batchNo" placeholder="请选择批次号" clearable size="small"
                   filterable remote :remote-method="remoteMethod" :loading="loading">
          <el-option v-for="dict in batchNoList" :key="dict.id" :label="dict.batchNumber"
                     :value="dict.batchNumber"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="原材料" name="first"><first /></el-tab-pane>
      <el-tab-pane label="生产过程" name="second"><second :batch-no="queryParams.batchNo" /></el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import * as WorkOrderApi from '@/api/production/workorder';
import * as MaterialApi from '@/api/storage/material';
import {listDept} from "@/api/system/dept";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";
import First from './first.vue';
import Second from './second.vue';

export default {
  name: "ProductionYield",
  components: {
    Treeselect,
    First,
    Second
  },
  data() {
    return {
      activeName: 'first',
      batchNoList: [],
      deptList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        workOrderNo: null,
        procedureWorkOrderId: null,
        procedureWorkOrderNo: null,
        planId: null,
        planNo: null,
        deptId: null,
        deptName: null,
        productId: null,
        productName: null,
        productCode: null,
        materialId: null,
        materialNo: null,
        materialName: null,
        procedureId: null,
        procedureCode: null,
        procedureName: null,
        deviceId: null,
        deviceCode: null,
        deviceName: null,
        planBeginTime: [],
        planEndTime: [],
        actualBeginTime: [],
        actualEndTime: [],
        daySendWorkNumber: null,
        status: null,
        createTime: [],
      },
    };
  },
  created() {
    this.getList();
    this.getDeptList();
  },
  methods: {
    /** 远程搜索批次号 */
    async remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        try {
          // 调用接口搜索批次号，使用batchNumber作为搜索条件
          const res = await MaterialApi.getMaterialPage({
            pageNo: 1,
            pageSize: 50,
            batchNumber: query // 使用batchNumber字段进行搜索
          });

          // 获取搜索结果
          let searchResults = res.data.list || [];

          // 使用Map进行去重，以batchNumber为key
          const uniqueMap = new Map();
          searchResults.forEach(item => {
            if (!uniqueMap.has(item.batchNumber)) {
              uniqueMap.set(item.batchNumber, item);
            }
          });

          // 转换回数组
          this.batchNoList = Array.from(uniqueMap.values());

          console.log('远程搜索批次号:', query, '去重后结果:', this.batchNoList);

        } catch (error) {
          console.error('远程搜索批次号失败:', error);
          this.batchNoList = [];
        } finally {
          this.loading = false;
        }
      } else {
        // 如果搜索框为空，重新加载默认数据
        await this.getDeptList();
      }
    },
    handleClick(e) {
      console.log(e._props.label, 'czq')
    },
    async getDeptList() {
      const res = await MaterialApi.getMaterialPage({pageNo: 1, pageSize: 50});
      let list = res.data.list || [];
      
      // 使用Map进行去重，以batchNumber为key
      const uniqueMap = new Map();
      list.forEach(item => {
        if (!uniqueMap.has(item.batchNumber)) {
          uniqueMap.set(item.batchNumber, item);
        }
      });
      
      // 转换回数组
      this.batchNoList = Array.from(uniqueMap.values());
    },

    /** 部门节点格式化 */
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    toDetail(id) {
      this.$router.push({
        path: '/production/detail',
        query: {id: id}
      });
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await WorkOrderApi.getWorkOrderPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除工单编号为"' + id + '"的数据项?')
      try {
        await WorkOrderApi.deleteWorkOrder(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除工单 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await WorkOrderApi.deleteWorkOrderList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有工单数据项?');
      try {
        this.exportLoading = true;
        const data = await WorkOrderApi.exportWorkOrderExcel(this.queryParams);
        this.$download.excel(data, '工单.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
  }
};
</script>
